<?php
$auth = Auth::getAuth('current_user');
$db = new Database;
$fs = new functions;
$upload = new upload();
$search = new Search();
if(isset($_POST['action'])){
	$date = $fs->currentDateTime();
	
	switch($_POST['action']){
		
		// Save workspace to the databasea
		
		case "saveWorkspace":
			//$workspace = $_POST['workspace'];
			$type = $_POST['type'];
			$json_return = array();
			$data = $_POST['json_encode'];
			$json = json_decode($data, true);
			$fields = $json['form_fields'];
			$formId =$_POST['formId'];
			$tblname =  $json['Title'];

				$tblname = $auth['company_id'].'_tbl_'.str_replace(' ','',$tblname);
			
				$workspace_content = str_replace('\\', '', $json['WorkspaceContent']);
				// Insert record to the database of tb_workspace	
				$insert = array("form_name"		=>	$json['Title'],
						"form_id"		=>	$json['formID'],
						"form_table_name"	=>	$tblname,
						"form_description"	=>	$json['DisplayName'],
						"form_content"		=>	$workspace_content,
						"form_buttons"		=>	$json['BtnName'],
						"created_by"		=>	$auth['id'],
						"updated_by"		=>	$auth['id'],
						"company_id"		=>	$auth['company_id'],
						"reference_prefix"	=>	$json['Prefix'],
						"reference_type"	=>	$json['Type'],
						"version"		=>	1,
						"form_json"		=>	$data,
						"date_created"		=>	$date,
						"button_content"	=>	$json['button_content'],
						"active_fields" 	=>  	$json["existing_fields"],
						"date_updated"		=>	$date,
						"is_active"		=>	1,
						"MobileJsonData"	=>	$json["MobileJsonData"],
						"MobileContent"		=>	$json["MobileContent"],
						"form_authors"		=>	$json["form_authors"],
						"form_viewers"		=>	$json["form_viewers"],
						"formTrackNo"		=>	$json["formtrackNo"],
						"formRequestID"		=>	$json["formrequestID"],
						"tab_object"		=>	$json["tab_object"],
						"generate_object"	=>	$json["generate_object"],
					);
				
				if($type!="update"){
					$workspaceID = $db->insert("tb_generate",$insert);
				}else{
					$workspaceID = $db->update("tb_generate",$insert,array("form_id"=>$formId));
				}
					
					$message = "Your form (" . $json['Title'] . ") was successfully created.";
					$json_return = array(	"status"=>"success",
								"message"=>$message,
								"id"=>$insert,
								"redirectURL"=>"application?id=".$fs->base_encode_decode("encrypt",$json['formID']));
					echo json_encode($json_return);
			break;
	
		case "loadWorkspace":
			$generateID = $_POST['generateID'];
			$getGenerate = $db->query("SELECT * FROM tb_generate WHERE id={$db->escape($generateID)} AND is_active={$db->escape(1)}","array");
			echo json_encode($getGenerate);
			
			break;
		
	}
	
}

?>